use crate::{
    ast::{types, Expression, Type},
    error::{CompilerError, Result},
    llvm_backend::LLVMBackend,
};
use inkwell::{types::BasicType, values::BasicValueEnum, AddressSpace};

impl<'ctx> LLVMBackend<'ctx> {
    /// Generate slice.reserve(n) method - preallocate capacity
    /// This ensures the slice has at least 'n' capacity, reallocating if necessary
    /// and freeing the old memory
    pub(in crate::llvm_backend) fn generate_slice_reserve_method(
        &mut self,
        var_name: &str,
        arguments: &[Expression],
    ) -> Result<BasicValueEnum<'ctx>> {
        // Validate arguments
        if arguments.len() != 1 {
            return Err(CompilerError::internal(
                "reserve() requires exactly one argument (capacity)",
            ));
        }

        // Get the slice variable pointer from variable_map
        let slice_ptr = self
            .variable_map
            .get(var_name)
            .ok_or_else(|| {
                CompilerError::internal(format!("Undefined slice variable: {}", var_name))
            })?
            .into_pointer_value();

        // Get the slice type
        let vector_type = self.variable_type_map.get(var_name).ok_or_else(|| {
            CompilerError::internal(format!("Undefined slice type for variable: {}", var_name))
        })?;

        let element_type = if let Type::Vec(slice_t) = vector_type {
            *slice_t.element_type.clone()
        } else {
            return Err(CompilerError::internal(
                "reserve() requires a slice variable",
            ));
        };

        // Get the element LLVM type
        let element_llvm_type = self.nrc_type_to_llvm_type(&Some(element_type.clone()))?;

        // Calculate element size. Default to pointer size for non-basic types,
        // except Rc/Weak trait handles which are {ptr, ptr}.
        let element_size = match &element_type {
            Type::Basic(basic_type) => match basic_type {
                types::BasicType::Int8 | types::BasicType::Uint8 | types::BasicType::Char => 1,
                types::BasicType::Int16 | types::BasicType::Uint16 => 2,
                types::BasicType::Int32 | types::BasicType::Uint32 | types::BasicType::Float32 => 4,
                types::BasicType::Int
                | types::BasicType::Int64
                | types::BasicType::Uint
                | types::BasicType::Uint64
                | types::BasicType::Float64 => 8,
                types::BasicType::Bool => 1,
                _ => 8,
            },
            Type::Rc(rc_type) => {
                if self.trait_name_from_type(&rc_type.inner_type).is_some() {
                    16
                } else {
                    8
                }
            }
            Type::Weak(weak_type) => {
                if self.trait_name_from_type(&weak_type.inner_type).is_some() {
                    16
                } else {
                    8
                }
            }
            _ => 8,
        };

        // Generate the requested capacity argument
        let requested_cap_value = self.generate_expression(&arguments[0])?;
        let mut requested_cap = requested_cap_value.into_int_value();

        // Convert to i64 if necessary
        if requested_cap.get_type() != self.context.i64_type() {
            requested_cap = self.builder.build_int_z_extend_or_bit_cast(
                requested_cap,
                self.context.i64_type(),
                "requested_cap_i64",
            )?;
        }

        // Create slice struct type
        let ptr_type = element_llvm_type.ptr_type(AddressSpace::default());
        let slice_struct_type = self.context.struct_type(
            &[
                ptr_type.into(),
                self.context.i64_type().into(),
                self.context.i64_type().into(),
            ],
            false,
        );

        // Load current slice
        let current_slice =
            self.builder
                .build_load(slice_struct_type, slice_ptr, "current_slice")?;

        if !current_slice.is_struct_value() {
            return Err(CompilerError::internal("Slice value is not a struct"));
        }

        let slice_struct = current_slice.into_struct_value();

        // Extract fields from the slice struct
        let old_ptr = self
            .builder
            .build_extract_value(slice_struct, 0, "old_ptr")?
            .into_pointer_value();
        let len = self
            .builder
            .build_extract_value(slice_struct, 1, "len")?
            .into_int_value();
        let old_cap = self
            .builder
            .build_extract_value(slice_struct, 2, "old_cap")?
            .into_int_value();

        // Check if we need to reallocate: requested_cap > old_cap
        let need_realloc = self.builder.build_int_compare(
            inkwell::IntPredicate::UGT,
            requested_cap,
            old_cap,
            "need_realloc",
        )?;

        // Create basic blocks for control flow
        let parent_fn = self
            .builder
            .get_insert_block()
            .and_then(|b| b.get_parent())
            .ok_or_else(|| CompilerError::internal("No parent function for reserve"))?;

        let realloc_block = self
            .context
            .append_basic_block(parent_fn, "reserve_realloc");
        let no_realloc_block = self
            .context
            .append_basic_block(parent_fn, "reserve_no_realloc");
        let merge_block = self.context.append_basic_block(parent_fn, "reserve_merge");

        // Branch based on whether reallocation is needed
        let _ =
            self.builder
                .build_conditional_branch(need_realloc, realloc_block, no_realloc_block);

        // Realloc block: allocate new memory, copy data, and free old memory
        self.builder.position_at_end(realloc_block);

        // Allocate new memory with requested capacity
        let element_size_const = self.context.i64_type().const_int(element_size, false);
        let new_size_bytes =
            self.builder
                .build_int_mul(requested_cap, element_size_const, "new_size_bytes")?;

        let malloc_func = self
            .function_map
            .get("__malloc")
            .ok_or_else(|| CompilerError::internal("malloc function not found"))?;
        let malloc_call =
            self.builder
                .build_call(*malloc_func, &[new_size_bytes.into()], "reserve_malloc")?;
        let new_ptr_i8 = malloc_call
            .try_as_basic_value()
            .left()
            .ok_or_else(|| CompilerError::internal("malloc call did not return a value"))?
            .into_pointer_value();

        let new_ptr = self
            .builder
            .build_bitcast(
                new_ptr_i8,
                element_llvm_type.ptr_type(AddressSpace::default()),
                "new_ptr_typed",
            )?
            .into_pointer_value();

        // Copy existing elements using memcpy
        let copy_size = self
            .builder
            .build_int_mul(len, element_size_const, "copy_size")?;

        // Get memcpy intrinsic
        let memcpy_intrinsic = self
            .module
            .get_function("llvm.memcpy.p0.p0.i64")
            .unwrap_or_else(|| {
                let i8_ptr_type = self.context.i8_type().ptr_type(AddressSpace::default());
                let memcpy_type = self.context.void_type().fn_type(
                    &[
                        i8_ptr_type.into(),
                        i8_ptr_type.into(),
                        self.context.i64_type().into(),
                        self.context.bool_type().into(),
                    ],
                    false,
                );
                self.module
                    .add_function("llvm.memcpy.p0.p0.i64", memcpy_type, None)
            });

        // Cast pointers to i8* for memcpy
        let dest_i8 = self
            .builder
            .build_bitcast(
                new_ptr,
                self.context.i8_type().ptr_type(AddressSpace::default()),
                "dest_i8",
            )?
            .into_pointer_value();

        let src_i8 = self
            .builder
            .build_bitcast(
                old_ptr,
                self.context.i8_type().ptr_type(AddressSpace::default()),
                "src_i8",
            )?
            .into_pointer_value();

        // Call memcpy to copy data
        self.builder.build_call(
            memcpy_intrinsic,
            &[
                dest_i8.into(),
                src_i8.into(),
                copy_size.into(),
                self.context.bool_type().const_int(0, false).into(),
            ],
            "memcpy_call",
        )?;

        // Free old memory
        let free_func = self
            .function_map
            .get("free")
            .ok_or_else(|| CompilerError::internal("free function not found"))?;
        self.builder
            .build_call(*free_func, &[src_i8.into()], "free_old_memory")?;

        let _ = self.builder.build_unconditional_branch(merge_block);

        // No realloc block: keep existing values
        self.builder.position_at_end(no_realloc_block);
        let _ = self.builder.build_unconditional_branch(merge_block);

        // Merge block: create PHI nodes for ptr and cap
        self.builder.position_at_end(merge_block);

        let ptr_phi = self.builder.build_phi(
            element_llvm_type.ptr_type(AddressSpace::default()),
            "final_ptr",
        )?;
        ptr_phi.add_incoming(&[(&new_ptr, realloc_block), (&old_ptr, no_realloc_block)]);
        let final_ptr = ptr_phi.as_basic_value().into_pointer_value();

        let cap_phi = self
            .builder
            .build_phi(self.context.i64_type(), "final_cap")?;
        cap_phi.add_incoming(&[
            (&requested_cap, realloc_block),
            (&old_cap, no_realloc_block),
        ]);
        let final_cap = cap_phi.as_basic_value().into_int_value();

        // Create new slice struct with updated values
        let new_slice_alloca = self.builder.build_alloca(slice_struct_type, "new_slice")?;

        // Store ptr field
        let ptr_field_ptr = unsafe {
            self.builder.build_gep(
                slice_struct_type,
                new_slice_alloca,
                &[
                    self.context.i32_type().const_int(0, false),
                    self.context.i32_type().const_int(0, false),
                ],
                "ptr_field",
            )?
        };
        self.builder.build_store(ptr_field_ptr, final_ptr)?;

        // Store len field (unchanged)
        let len_field_ptr = unsafe {
            self.builder.build_gep(
                slice_struct_type,
                new_slice_alloca,
                &[
                    self.context.i32_type().const_int(0, false),
                    self.context.i32_type().const_int(1, false),
                ],
                "len_field",
            )?
        };
        self.builder.build_store(len_field_ptr, len)?;

        // Store cap field (updated)
        let cap_field_ptr = unsafe {
            self.builder.build_gep(
                slice_struct_type,
                new_slice_alloca,
                &[
                    self.context.i32_type().const_int(0, false),
                    self.context.i32_type().const_int(2, false),
                ],
                "cap_field",
            )?
        };
        self.builder.build_store(cap_field_ptr, final_cap)?;

        // Load the new slice
        let new_slice =
            self.builder
                .build_load(slice_struct_type, new_slice_alloca, "new_slice")?;

        // Store the new slice back to the variable
        self.builder.build_store(slice_ptr, new_slice)?;

        // Return void (0)
        Ok(self.context.i32_type().const_int(0, false).into())
    }
}
